# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def swapNodes(self, head: ListNode, k: int) -> ListNode:
        n = 0
        node = head
        while node:
            node = node.next
            n += 1
        if n == 1:
            return head
        c = 0
        node = head
        a = k
        b = n - k + 1
        aPre = None
        aNext = None
        bPre = None
        bNext = None
        aNode = None
        bNode = None
        dummy = ListNode(-1)
        dummy.next = head
        node = dummy
        while node:
            if c == a - 1:
                aPre = node
            if c == a + 1:
                aNext = node
            if c == b - 1:
                bPre = node
            if c == b + 1:
                bNext = node
            if c == a:
                aNode = node
            if c == b:
                bNode = node
            node = node.next
            c += 1
        if b - a == 1:
            aPre.next = bNode
            bNode.next = aNode
            aNode.next = bNext
            return dummy.next
        elif a - b == 1:
            bPre.next = aNode
            aNode.next = bNode
            bNode.next = aNext
            return dummy.next
        aPre.next = bNode
        bNode.next = aNext
        bPre.next = aNode
        aNode.next = bNext

        return dummy.next


if __name__ == '__main__':
    node1 = ListNode(1)
    node2 = ListNode(2)
    node1.next = node2
    node = Solution().swapNodes(node1, 1)
    print(node)
